<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled, Download, Delete, Search } from '@element-plus/icons-vue'
import { useFileStore } from '@/stores/file'
import axios from 'axios'
// 文件列表数据
const fileList = ref([])
const files = ref([])
const folderList = ref([])
const currentFolderId = ref('root') // 当前文件夹ID，根目录为'root'
const useStore = useFileStore()

// 分页数据
const pagination = computed(() => useStore.pagination)

// 上传状态
const uploading = ref(false);

// 文件搜索
const searchKeyword = ref('')
const searching = ref(false)

// 显示支持的文件类型
const showSupportedTypes = ref(false)

// 获取支持的文件扩展名列表
const getSupportedFileExtensions = () => {
  return [
    // 图片文件
    '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg',
    // 文档文件  
    '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx',
    // 文本文件
    '.txt', '.md', '.csv', '.json', '.html', '.css', '.js',
    // 压缩文件
    '.zip', '.rar', '.7z', '.gz',
    // 音频文件
    '.mp3', '.wav', '.ogg', '.m4a',
    // 视频文件
    '.mp4', '.avi', '.mov',
    // 其他
    '.xml', '.sql'
  ]
}

// 获取文件列表
const fetchFileList = async (keyword = '') => {
  try {
    searching.value = true
    // 调用API获取文件列表
    const response = await useStore.getfiles(keyword);
    console.log(response.files)
    fileList.value = response.files
    console.log(response);
  } catch (error) {
    ElMessage.error('获取文件列表失败')
    console.error(error)
  } finally {
    searching.value = false
  }
}
const handleFileChange = (uploadFile) => {
  const file = uploadFile.raw
  const isLessThan10MB = file.size / 1024 / 1024 < 10
  const allowedTypes = [
    // 图片文件
    'image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp', 'image/svg+xml',
    // 文档文件
    'application/pdf',
    'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    // 文本文件
    'text/plain', 'text/markdown', 'text/csv', 'application/json', 'text/html', 'text/css', 'application/javascript',
    // 压缩文件
    'application/zip', 'application/x-rar-compressed', 'application/x-7z-compressed', 'application/gzip',
    // 音频文件
    'audio/mpeg', 'audio/wav', 'audio/ogg', 'audio/mp4',
    // 视频文件
    'video/mp4', 'video/avi', 'video/quicktime', 'video/x-msvideo',
    // 其他常用格式
    'application/xml', 'application/x-sql'
  ]
  const isAllowedType = allowedTypes.includes(file.type)

  if (!isLessThan10MB) {
    ElMessage.error('文件大小不能超过10MB！')
    return
  }
  if (!isAllowedType) {
    ElMessage.error(`不支持的文件类型！当前文件类型：${file.type || '未知'}，请选择支持的文件格式`)
    return
  }

  files.value.push(file) // ✅ 合法文件才 push
  
  ElMessage.success(`文件 ${file.name} 已选择，等待上传`)
}

// 处理文件移除
const handleFileRemove = (uploadFile) => {
  const index = files.value.findIndex(file => file.name === uploadFile.name && file.size === uploadFile.size)
  if (index > -1) {
    files.value.splice(index, 1)
  }
}


/**
 * 手动上传文件到服务器
 */
// const uploadFiles = async () => {
//   if (fileList.value.length === 0) {
//     ElMessage.warning('请先选择文件！');
//     return;
//   }
//   console.log(1111);

//   uploading.value = true;

//   try {
//     // 1. 创建 FormData 对象
//     const formData = new FormData();

//     // 2. 将所有文件添加到 FormData (字段名必须与后端一致)
//     // 注意: 根据错误信息，后端期望的字段名是 'file' (不是 'files')
//     fileList.value.forEach((file) => {
//       formData.append('file', file); // 关键: 使用 'file' 作为字段名
//     });

//     // 3. 发送请求 (替换为你的实际 API 地址)
//     // 注意: 这里假设 useStore.uploadfiles 是封装好的上传方法
//     // 如果没有封装，可以直接用 axios:
//     /*
//     const response = await axios.post('/api/files/upload', formData, {
//       headers: {
//         'Authorization': `Bearer ${token.value}`,
//         // 不要手动设置 Content-Type，让浏览器自动处理 multipart/form-data
//       }
//     });
//     */
//     console.log('准备发送请求...', formData);
//     // const response = await axios.post('/api/files/upload',formData,{
//     //   headers:{
//     //     'Authorization':`Bearer ${useStore.token}`
//     //   }
//     // }) // 假设 useStore 已正确实现
//     const response = await useStore.uploadfiles(formData); // 假设 useStore 已正确实现
//     // 4. 上传成功处理
//     ElMessage.success('文件上传成功！');
//     fetchFileList()
//     // 5. 清空文件列表
//     // fileList.value = [];//
//   } catch (error) {
//     if (error.response) {
//       // 服务器返回了响应，但状态码是 4xx/5xx
//       console.error('上传失败详情:', {
//         status: error.response.status,
//         data: error.response.data,
//         headers: error.response.headers
//       });
//       ElMessage.error('上传失败: ' + (error.response.data?.message || '服务器错误'));
//     } else if (error.request) {
//       // 请求已发出，但没有收到响应（网络错误、跨域问题等）
//       console.error('无响应详情:', {
//         request: error.request
//       });
//       ElMessage.error('网络错误，请检查连接或跨域设置');
//     } else {
//       // 其他错误（如代码逻辑错误）
//       console.error('未知错误:', error.message);
//       ElMessage.error('上传失败: ' + error.message);
//     }
//   } finally {
//     uploading.value = false;
//   }
// };

const uploadFiles = async () => {
  if (!files.value.length) return ElMessage.warning('请先选择文件')

  uploading.value = true
  const form = new FormData()
  files.value.forEach(f => form.append('file', f))

  try {
    await axios.post('/api/files/upload', form, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    })
    ElMessage.success('上传成功')

    //立即刷新列表，保持当前搜索状态
    await fetchFileList(searchKeyword.value)

    files.value = [] // 清空
  } catch (e) {
    ElMessage.error(e.response?.data?.message || '上传失败')
  } finally {
    uploading.value = false
  }
}


// 上传下一个文件
const formatDate = (time) => {
  if (!time) return '';
  const date = new Date(time);
  const beijingTime = new Date(date.getTime() + 8 * 3600 * 1000); // 转换为北京时间
  return beijingTime.toISOString().replace('T', ' ').substring(0, 19); // 格式化为 YYYY-MM-DD HH:MM:SS
};
// 删除文件

const confirmDelete = (fileId) => {
  ElMessageBox.confirm(
    '确定要删除此文件吗？此操作不可恢复。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    handleDelete(fileId); // 调用实际删除方法
  }).catch(() => {
    // 用户取消删除
  });
};
const handleDelete = async (fileId) => {
  try {
    // 调用删除API
    await useStore.deleteFile(fileId);

    ElMessage.success('文件删除成功！');

    // 刷新文件列表，保持当前搜索状态
    fetchFileList(searchKeyword.value);
  } catch (error) {
    ElMessage.error('文件删除失败: ' + error.message);
  }
};
const downloading = ref(false);

// 下载文件
const handleDownload = async (fileId, fileName) => {
  try {
    downloading.value = true;
    
    const response = await axios.get(`/api/files/${fileId}/download`, {
      responseType: 'blob',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });

    // 使用传入的文件名或从响应头获取
    let downloadFileName = fileName || `file_${fileId}`;
    
    const disposition = response.headers['content-disposition'];
    if (disposition) {
      const match = disposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
      if (match && match[1]) {
        downloadFileName = match[1].replace(/['"]/g, '');
      }
    }

    // 创建下载链接
    const url = window.URL.createObjectURL(response.data);
    const link = document.createElement('a');
    link.href = url;
    link.download = downloadFileName;
    document.body.appendChild(link);
    link.click();

    // 清理
    setTimeout(() => {
      window.URL.revokeObjectURL(url);
      document.body.removeChild(link);
    }, 100);

    ElMessage.success('文件下载成功！');
  } catch (error) {
    console.error('下载错误:', error);
    
    // 友好的错误提示
    if (error.response?.status === 404) {
      ElMessage.error('下载失败，文件不存在');
    } else if (error.response?.status === 403) {
      ElMessage.error('下载失败，没有权限访问该文件');
    } else if (error.response?.status === 401) {
      ElMessage.error('下载失败，请先登录');
    } else if (error.response?.status >= 500) {
      ElMessage.error('下载失败，服务器内部错误');
    } else if (error.response?.data?.message) {
      ElMessage.error(`下载失败：${error.response.data.message}`);
    } else if (error.code === 'NETWORK_ERROR' || !error.response) {
      ElMessage.error('下载失败，网络连接错误');
    } else {
      ElMessage.error('下载失败，请稍后重试');
    }
  } finally {
    downloading.value = false;
  }
}
// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 搜索文件
const searchFiles = async () => {
  // 重置到第一页
  useStore.setPagination(1, pagination.value.pageSize)
  // 调用API搜索文件
  await fetchFileList(searchKeyword.value)
  console.log('搜索关键词:', searchKeyword.value)
}

// 清空搜索
const clearSearch = async () => {
  searchKeyword.value = ''
  useStore.setPagination(1, pagination.value.pageSize)
  await fetchFileList()
}

// 分页改变处理
const handlePageChange = async (page) => {
  useStore.setPagination(page, pagination.value.pageSize)
  await fetchFileList(searchKeyword.value)
}

// 每页大小改变处理
const handleSizeChange = async (size) => {
  useStore.setPagination(1, size)
  await fetchFileList(searchKeyword.value)
}

// 进入文件夹
const enterFolder = (folder) => {
  currentFolderId.value = folder.id
  fetchFileList()
}

onMounted(() => {
  fetchFileList()
})
</script>

<template>
  <div class="file-management-system">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <h2>文件管理系统</h2>
          <div class="header-actions">
            <el-input 
              v-model="searchKeyword" 
              placeholder="搜索文件名称..." 
              prefix-icon="Search" 
              clearable 
              @clear="clearSearch"
              @keyup.enter="searchFiles" 
              class="search-input"
              :loading="searching"
            />
            <el-button 
              type="primary" 
              :icon="Search" 
              @click="searchFiles"
              :loading="searching"
            >
              {{ searching ? '搜索中...' : '搜索' }}
            </el-button>
          </div>
        </div>
      </template>

      <!-- 面包屑导航 -->
      <!-- <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item @click="currentFolderId = 'root'; fetchFileList()">根目录</el-breadcrumb-item>
        <el-breadcrumb-item 
          v-for="folder in getFolderPath(currentFolderId)" 
          :key="folder.id"
          @click="currentFolderId = folder.id; fetchFileList()"
        >
          {{ folder.name }}
        </el-breadcrumb-item>
      </el-breadcrumb> -->

      <!-- 文件夹操作 -->
      <!-- <div class="folder-actions">
        <el-button type="primary" :icon="FolderAdd" @click="showNewFolderDialog = true">
          创建文件夹
        </el-button>
      </div>

      // 新建文件夹对话框 
      <el-dialog v-model="showNewFolderDialog" title="创建文件夹" width="30%">
        <el-input v-model="newFolderName" placeholder="请输入文件夹名称" />
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showNewFolderDialog = false">取消</el-button>
            <el-button type="primary" @click="handleCreateFolder">确认</el-button>
          </span>
        </template>
      </el-dialog> -->

      <!-- 文件上传 -->
      <div class="upload-area">
        <!-- <el-upload class="upload-component" drag :auto-upload="false" :on-change="handleFileChange"
          :show-file-list="false" multiple
          accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.zip,.rar"
          :http-request="uploadFiles">
          <el-icon class="el-icon--upload">
            <UploadFilled />
          </el-icon>
          <div class="el-upload__text">
            拖拽文件到此处或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持多文件上传，文件大小不超过5MB，仅支持特定文件格式
            </div>
          </template>
        </el-upload>
        <el-button type="primary" @click="uploadFiles" :loading="uploading" :disabled="fileList.length === 0">
          {{ uploading ? "上传中..." : "开始上传" }}
        </el-button> -->
        <el-upload
            drag
            multiple
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :show-file-list="true"
            accept=".jpg,.jpeg,.png,.gif,.bmp,.webp,.svg,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.md,.csv,.json,.html,.css,.js,.zip,.rar,.7z,.gz,.mp3,.wav,.ogg,.m4a,.mp4,.avi,.mov,.xml,.sql"
          >
            <el-icon><UploadFilled /></el-icon>
            <div>拖拽或点击选择文件</div>
            <template #tip>
              <div class="el-upload__tip">
                支持图片、文档、音视频、压缩包等多种格式，文件大小不超过10MB
                <el-button 
                  link 
                  type="primary" 
                  size="small" 
                  @click="showSupportedTypes = !showSupportedTypes"
                  style="margin-left: 10px;"
                >
                  {{ showSupportedTypes ? '隐藏' : '查看' }}支持的文件类型
                </el-button>
                <div v-if="showSupportedTypes" class="supported-types">
                  <p><strong>支持的文件类型：</strong></p>
                  <div class="file-types-grid">
                    <span v-for="ext in getSupportedFileExtensions()" :key="ext" class="file-type-tag">{{ ext }}</span>
                  </div>
                </div>
              </div>
            </template>
          </el-upload>
        
          <el-button
            type="primary"
            @click="uploadFiles"
            :loading="uploading"
            :disabled="!files.length"
          >
            {{ uploading ? '上传中...' : '开始上传' }}
          </el-button>
      </div>
      <!-- 可选：显示已选择的文件列表 -->
      <!-- <div v-if="fileList.length > 0" class="selected-files">
            <div v-for="(file, index) in fileList" :key="index" class="file-item">
              <span>{{ file.name }}</span>
              <el-button @click="removeFile(index)" size="small" type="danger">删除</el-button>
            </div>
          </div> -->

      <!-- 上传按钮 -->


      <!-- 上传进度 -->
      <div v-if="uploading" class="upload-progress">
        <el-progress :percentage="100" status="success" :show-text="false" />
        <p class="upload-text">文件上传中，请稍候...</p>
      </div>

      <!-- 文件列表 -->
      <div v-if="fileList.length || folderList.length" class="file-list-container">
        <!-- 文件夹列表 -->
        <div v-if="folderList.length" class="folder-list">
          <h3>文件夹</h3>
          <el-table :data="folderList" style="width: 100%" size="small">
            <el-table-column prop="name" label="文件夹名称" />
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button link type="primary" :icon="Download" @click="enterFolder(scope.row)">
                  进入
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 文件列表 -->
        <div class="file-list">
          <h3>文件列表</h3>
          <el-table :data="fileList" style="width: 100%" size="small" v-loading="searching">
            <el-table-column prop="id" label="文件Id" show-overflow-tooltip />
            <el-table-column prop="name" label="文件名称" min-width="200" show-overflow-tooltip />
            <el-table-column prop="mimeType" label="文件类型" width="120" />
            <el-table-column prop="size" label="文件大小" width="120">
              <template #default="{ row }">
                {{ formatFileSize(row.size) }} <!-- 新增格式化方法 -->
              </template>
            </el-table-column>
            <el-table-column label="上传时间" width="160">
              <template #default="{ row }">
                {{ formatDate(row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column prop="username" label="上传者" width="120" />
            <el-table-column label="操作" width="200">
              <template #default="{ row }">
                <el-button link type="primary" :icon="Download" @click="handleDownload(row.id, row.name)">
                  下载
                </el-button>
                <el-button link type="danger" :icon="Delete" @click="confirmDelete(row.id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页组件 -->
          <div class="pagination-container" v-if="fileList.length > 0">
            <el-pagination
              v-model:current-page="pagination.page"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="pagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
              background
            />
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else-if="!searching" class="empty-state">
        <el-empty description="暂无文件或文件夹">
          <template v-if="searchKeyword">
            <p>搜索关键词 "{{ searchKeyword }}" 没有找到相关文件</p>
            <el-button type="primary" @click="clearSearch">清空搜索</el-button>
          </template>
        </el-empty>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.file-management-system {
  padding: 20px;
}

.main-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.breadcrumb {
  margin-bottom: 20px;
}

.folder-actions {
  margin-bottom: 20px;
}

.upload-area {
  margin-bottom: 20px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #409EFF;
}

.upload-component {
  width: 100%;
}

.upload-area {
  margin: 20px 0;
}

.selected-files {
  margin: 10px 0;
}

.file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 0;
  border-bottom: 1px solid #eee;
}

.upload-progress {
  margin-bottom: 20px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.file-list-container {
  margin-top: 20px;
}

.folder-list,
.file-list {
  margin-bottom: 20px;
}

.empty-state {
  margin-top: 50px;
  text-align: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px 0;
}

.search-input {
  width: 300px;
}

/* 搜索加载状态 */
.el-input.is-loading .el-input__inner {
  opacity: 0.7;
}

.upload-progress {
  margin: 20px 0;
  text-align: center;
}

.upload-text {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}

.supported-types {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  text-align: left;
}

.file-types-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-top: 8px;
}

.file-type-tag {
  display: inline-block;
  padding: 2px 6px;
  background-color: #e4e7ed;
  color: #606266;
  border-radius: 3px;
  font-size: 12px;
  font-family: monospace;
}
</style>